<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

/**
 * 耗时异步操作（调用本地程序）
 * @param $url   模板      模块名称/控制器/方法?参数名=参数值
 * */
function  asyncronous($url,$params=array()){
	if(empty($url)){
		return array("flag"=>false,"msg"=>"参数不正确");
	}
	if(strpos($url, "/")==0){
		return array("flag"=>false,"msg"=>"参数格式错误");
	}
	if(!empty($params)&&is_array($params)){
		$url.="?t=1";
		foreach ($params as $key => $value) {
			$url.="&".$key."=".$value;
		}
	}
	$server=$_SERVER['HTTP_HOST'];
    $fp = fsockopen($server,80,$errno,$errstr,5); 
    	if(!$fp){
    		return array("flag"=>false,"msg"=>"$errstr ($errno)");
         }
    $out = "GET /$url  / HTTP/1.1\r\n";
	$out .= "Content-type: application/json\r\n";
    $out .= "Host: $server\r\n";
    $out .= "Connection: Close\r\n\r\n";
	fwrite($fp, $out);
	$result='';
    fclose($fp); 
}
/**
 * 耗时异步操作（调用外部程序）
 */
function aysncronous_out($url,$params=array()){
  $host = config("database.asyn_base").$url;
  if(!empty($params)&&is_array($params)){
		$host.="?t=1";
		foreach ($params as $key => $value) {
			$host.="&".$key."=".$value;
		}
	}
	  $ch = curl_init();
	  curl_setopt($ch,CURLOPT_URL,$host);
	  curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
	  curl_setopt($ch,CURLOPT_TIMEOUT,1);
	  $result = curl_exec($ch);
	  curl_close($ch);
	  return $result;
}
/**
 * 数据库备份
 * */
function db_dump(){
	$today=date("Y-m-d");
	$count=db("SqlBack")->where("create_time like '%$today%'")->count(1);
	if(!empty($count)){
		var_dump("已经备份");
		return FALSE;
	}	
	vendor("dg.mysql-dump.src.MySQLDump");
	$dump=new MySqlDump(new mysqli(config("database.hostname"),config("database.username"),config("database.password"),config("database.database")));
	$file_name="./data/sqlbackup/".date("ymd").".sql.gz";
	$dump->save($file_name);
	db("SqlBack")->insert(array("shop_name"=>config("database.shop_name"),"shop_id"=>config("database.shop_id"),"url"=>$file_name,"ip"=>(request()->ip())));
	return date("ymd").".sql.gz";
}

/***
 * $url 
 * $param=array('id'=>'1','name'=>'sharx');
 */
function post_submit_xml($url,$params){
	$client = new \GuzzleHttp\Client();
	try{
		$response=$client->request('POST',$url, [
		'form_params' => $params]);	
	}catch(Exception $e){
		throw $e;
	}
	if($response->getStatusCode()!=200){
		return  null;
	}else{
		$result=$response->getBody()->getContents();
		$obj=json_decode(json_encode(simplexml_load_string($result),TRUE),TRUE);
		if(empty($obj)){
			return null;
		}else{
			return $obj;
		}
	}
}
/**
 * http://docs.guzzlephp.org/en/stable/
 *  http post 请求
 */
function http_post($url,$params){
 	    //延迟不操作3秒
	$client = new \GuzzleHttp\Client(['timeout'  => 3.0,'verify'=>FALSE]);
	try{
		$response=$client->request('POST',$url,["form_params"=>$params]);	
		$result=$response->getBody()->getContents();
		return template_success("成功",$result);
	}catch(\GuzzleHttp\Exception\ConnectException $conne){
		return template_error("网络链接超时");
	}catch(Exception $e){
		throw $e;
	}
}

/**
 * http://docs.guzzlephp.org/en/stable/
 * http get 请求
 */
 function http_get($url,$params){
 	    //延迟不操作3秒
 		$client = new \GuzzleHttp\Client(['timeout'  => 3.0,'verify'=>FALSE]);
		try{
			$response=$client->request('GET',$url,["query"=>$params]);	
			$result=$response->getBody()->getContents();
			return template_success("成功",$result);
		}catch(\GuzzleHttp\Exception\ConnectException $conne){
			return template_error("网络链接超时");
		}catch(Exception $e){
			throw $e;
		}
 }
 /**
  * xml 和json 互转
  * @param $xmlstr 字符串
  * @param $has_namespace str 中是否包括 命名空间  0 不包括 1 包含 
  */
 function xml_json($xmlstr,$has_namespace=0){
    if($has_namespace==1){
     $xmlstr = preg_replace('/\sxmlns="(.*?)"/', ' _xmlns="${1}"', $xmlstr);
     $xmlstr = preg_replace('/<(\/)?(\w+):(\w+)/', '<${1}${2}_${3}', $xmlstr);
     $xmlstr = preg_replace('/(\w+):(\w+)="(.*?)"/', '${1}_${2}="${3}"', $xmlstr);	
    }
	$obj=json_decode(json_encode(simplexml_load_string($xmlstr),TRUE),TRUE);
	if(empty($obj)){
		return null;
	}else{
		return $obj;
	}
 }
 /**
  * 成功的模板
  */
 function template_success($msg="成功",$data=""){
 	return array("flag"=>TRUE,"msg"=>$msg,"data"=>$data);
 }
 /**
  * 失败的模板
  */
  function template_error($msg="失败",$data=""){
 	return array("flag"=>FALSE,"msg"=>$msg,"data"=>$data);
 }
/**
 * post  json 数据
 * @param $url 数据链接
 * @param $data 参数array()
 */
 function post_json($url,$data,$headers=""){
	$data_string = json_encode($data,TRUE);
	$ch = curl_init($url);
	curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
	curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3);//3s 超时
	$p_headers=array('Content-Type: application/json', 'Content-Length: ' . strlen($data_string));
	if(!empty($headers)){
		$p_headers=array_merge(array('Content-Type: application/json', 'Content-Length: ' . strlen($data_string)),$headers);
	}
	curl_setopt($ch, CURLOPT_HTTPHEADER,$p_headers);
	$response  = curl_exec($ch);
	curl_close($ch);
	return json_decode($response,TRUE);		
 }
 
 /**
 * post  json 数据
 * @param $url 数据链接
 * @param $data 参数array()
 */
 function get_json($url,$data,$headers=""){
	$data_string = json_encode($data,TRUE);
	if(!empty($data)){
		$url=$url."?".http_build_query($data);		
	}
	$ch = curl_init($url);
	curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3);//3s 超时
	if(!empty($headers)){
		curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);
	}	
	$response  = curl_exec($ch);
	curl_close($ch);
	return json_decode($response,TRUE);		
 }
